/**
 * 
 * @param {*} browser 
 * @param {*} page 
 * @returns 
 */
const SwitchToPharos = async (browser, page) => {
    const Switch = await page.locator('xpath=//button[text()="Switch >"]').all()
    if (Switch.length > 0){
        console.log('需要切换网络')
        const [newPage] = await Promise.all([
            browser.waitForEvent('page'), // 等待新窗口打开
            Switch[0].click(),
            console.log('点击Switch')
        ]);
        await newPage.waitForLoadState('networkidle');
        await newPage.locator('xpath=//button[@data-testid="confirmation-submit-button"]').click()
    }
}

/**
 * 连接钱包后继续
 * @param {*} browser
 * @param {*} page
 */
const continueAfterconnectWallet  = async (browser, page) => {
    const Continue = await page.locator('xpath=//button[text()="Continue"]').all();
    if (Continue.length > 0){
        const [newPage] = await Promise.all([
            browser.waitForEvent('page', {timeout:24000}), // 等待新窗口打开
            Continue[0].click(),
            console.log('点击继续按钮')
        ]);
        await newPage.waitForLoadState('networkidle', {timeout:24000});
        console.log('点击确认')
        await newPage.locator('xpath=//button[@data-testid="confirm-footer-button"]').click()
        await page.waitForTimeout(2000); // 等待2秒
    }
}

/**
 * 连接钱包
 * @param {*} browser
 * @param {*} page
 * @example connectWallet(browser, page)
 */
const connectWallet = async (browser, page) => {
    console.log("开始连接钱包!")
    await page.goto('https://testnet.pharosnetwork.xyz/experience?inviteCode=0g3rAsAm5zXOxwrc', {
        timeout:480000
    })
    await page.waitForLoadState('networkidle', {timeout:240000}) // 等待页面完全加载
    const Wallet = await page.locator("xpath=//button[text()='Connect Wallet']").all();
    if (Wallet.length === 0){
        console.log('已经连接钱包')
        await SwitchToPharos(browser, page);
        await page.waitForTimeout(2000); // 等待2秒
        await continueAfterconnectWallet(browser, page)
        return;
    }
    await Wallet[0].click()
    console.log('点击连接钱包按钮')
    const shadowHost = await page.$('w3m-modal.open');
    let shadowRoot = await shadowHost.evaluateHandle(host => host.shadowRoot);
    const widget = await shadowRoot.$('w3m-connect-announced-widget');
    shadowRoot = await widget.evaluateHandle(host => host.shadowRoot);
    const tag = await shadowRoot.$('wui-tag');
    const textContent = await tag.textContent();
    if (textContent !== 'installed'){
        console.log('未安装钱包');
        return;
    }
    const [xhlLoginpage] = await Promise.all([
        browser.waitForEvent('page', {timeout:240000}), // 等待新窗口打开
        tag.click(), // 点击触发新窗口的按钮
        console.log('点击钱包')
    ]);
    // 等待新页面加载
    await xhlLoginpage.waitForLoadState('networkidle', {timeout:240000});
    if (xhlLoginpage){
        console.log('新页面加载完成')
        await xhlLoginpage.locator('xpath=//*[@id="password"]').fill('12345678');
        await xhlLoginpage.locator('xpath=//button[@data-testid="unlock-submit"]').click();
        try {
            await xhlLoginpage.locator('xpath=//button[@data-testid="confirm-btn"]').click()
        } catch (error) {
            console.log('没有确认按钮')
        }
        await page.waitForTimeout(2000); // 等待2秒
        await SwitchToPharos(browser, page);
        await page.waitForTimeout(2000); // 等待2秒
        await continueAfterconnectWallet(browser, page)
    }
};

module.exports = { connectWallet };